﻿using gheat;
using GMap.NET;
using GMap.NET.Projections;
using GMap.NET.WindowsForms;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GMap.Test
{
   public class HeatMapOverlay: GMapOverlay
   {
      public GMapControl MapControl { get; set; }
      public PointManager Points { get; set; }
      MercatorProjection projection = new GMap.NET.Projections.MercatorProjection();

      public HeatMapOverlay(string name, GMapControl mapControl, params PointLatLng[] points)
      {
         MapControl = mapControl;
         Points = new gheat.PointManager();

         foreach (PointLatLng point in points)
            Points.AddPoint(point);
      }

      public override void OnRender(Graphics g)
      {
         base.OnRender(g);

         int oX = -MapControl.Width / 2;
         int oY = -MapControl.Height / 2;
         int offsetX = (int)g.ClipBounds.X - oX;
         int offsetY = (int)g.ClipBounds.Y - oY;

         GPoint pixelTopLeft = projection.FromLatLngToPixel(MapControl.ViewArea.LocationTopLeft, (int)MapControl.Zoom);
         GPoint pixelBottomRight = projection.FromLatLngToPixel(MapControl.ViewArea.LocationRightBottom, (int)MapControl.Zoom);

         GPoint startTile = projection.FromPixelToTileXY(pixelTopLeft);
         GPoint lastTile = projection.FromPixelToTileXY(pixelBottomRight);

         GPoint mapPosition = MapControl.PositionPixel;

         int minx = (int)startTile.X;
         int maxX = (int)lastTile.X;

         for (int x = minx; x <= maxX; x++)
         {
            for (int y = (int)startTile.Y; y <= lastTile.Y; y++)
            {
               Bitmap tempImage = gheat.GHeat.GetTile(Points, "classic", (int)MapControl.Zoom, x, y);
               //new FormImage().ShowDialogImage(tempImage);
               g.DrawImage(tempImage, new System.Drawing.PointF(x * 256 - mapPosition.X + +offsetX, y * 256 - mapPosition.Y + offsetY));
            }
         }
      }
   }
}
